package com.example.securitymy.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Date;
import java.util.UUID;

public class JwtUtil {
    private static final Long JWT_TTL = 60 * 60 *1000L;
    private static final String JWT_KEY = "jwtkey";

    /**
     * 获取uuid
     * 使用uuid作为token,然后从jwt中解析uuid后去redis取得用户信息
     * @return
     */
    public static String getUUID() {
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        return uuid;
    }

    /**
     * 生成jwt
     * @param subject
     * @return
     */
    public static String createJWT(String subject) {
        JwtBuilder builder=getJwtBuilder(subject,null,getUUID());
        return builder.compact();
    }

    /**
     *
     * @param subject jwt要存放的数据
     * @param ttlMillis 过期时间
     * @return
     */
    public static String createJWT(String subject,Long ttlMillis) {
        JwtBuilder builder=getJwtBuilder(subject,ttlMillis,getUUID());
        return builder.compact();
    }

    /**
     * 生成jwt
     * @param id
     * @param subject
     * @param ttlMillis 过期时间
     * @return
     */
    public static String createJWT(String subject, Long ttlMillis,String id) {
        JwtBuilder builder = getJwtBuilder(subject, ttlMillis, id);// 设置过期时间
        return builder.compact();
    }

    /**
     * 生成加密后的密钥
     * @return
     */
    public static SecretKey generalKey() {
        byte[] encodedKey = Base64.getDecoder().decode(JwtUtil.JWT_KEY);
        SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
        return key;
    }

    /**
     * 构建jwt
     * @param subject
     * @param ttlMillis
     * @param uuid
     * @return
     */
    private static JwtBuilder getJwtBuilder(String subject,Long ttlMillis,String uuid) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        SecretKey secretKey = generalKey();
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        // 不设置过期时间则使用默认过期时间
        if (ttlMillis == null) {
            ttlMillis = JwtUtil.JWT_TTL;
        }
        //过期的日期等于现在的日期加上过期时间
        long expMillis = nowMillis + ttlMillis;
        Date expDate = new Date(expMillis);
        return Jwts.builder().setId(uuid)//唯一的ID
                .setSubject(subject)// 主题  可以是JSON数据
                .setIssuer("sg")// 签发者
                .setIssuedAt(now)// 签发时间
                .signWith(signatureAlgorithm, secretKey)// 签名算法以及密匙
                .setExpiration(expDate);
    }
    /**
     * 解析jwt
     */
    public static Claims parseJWT(String jwt) {
        SecretKey secretKey = generalKey();
        return Jwts.parser()
                .setSigningKey(secretKey)
                .parseClaimsJws(jwt)
                .getBody();
    }
    public static void main(String[] args) throws Exception {
        long gristmills = 60 * 60 * 1000L;
        String token = createJWT(null,gristmills,"555");
        System.out.println(token);
        Claims claims = parseJWT(token);
        System.out.println(claims);

    }

}
